/*
 * TagEntity.java
 *
 * Created on July 3, 2007, 12:37 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.semanticvoid.lifelogger.entity;

import com.semanticvoid.lifelogger.db.DbInterface;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Vector;

/**
 *
 * @author anand_kishore
 */
public class TagEntity {
    
    /** Tag (Tag Text) */
    private String tag;
    
    /** List of entity guids using this tag */
    private Vector<String> guids;
    
    /** Term vector for Tag entity (Cumilative Term Vectors of all the guid entities) */
    private Map<String, Integer> termVector = null;
    
   
    /** Creates a new instance of TagEntity */
    public TagEntity(String tag) {
        this.tag = tag.toLowerCase();
        //this.dbi = dbi;

        // aggregate the guids using this tag
        collectGuids();
    }
    
    private void collectGuids() {
        guids = DbInterface.getEntityGuidsForTag(this.tag);
    }
    
    public boolean formTermVector() {
        if(this.getTermVector() == null) {
            this.termVector = new HashMap<String, Integer>();
        } else {
            return true;
        }
        
        for(String guid : guids) {
            String termVector = DbInterface.getTermVectorForEntity(guid);
            BrowseHistoryEntity bEntity = new BrowseHistoryEntity(guid);
            bEntity.setTermVector(termVector);
            
            Map<String, Integer> tVector = bEntity.getTermVector();
            
            if(tVector != null) {
                Set<String> tokens = tVector.keySet();
                
                if(tokens != null) {
                    for(String token : tokens) {
                        token = token.toLowerCase().trim();
                        int count;
                        
                        try {
                            count = tVector.get(token);
                        } catch(NullPointerException npe) {
                            continue;
                        }
                        
                        if(this.getTermVector().containsKey(token)) {
                            int pre_count = this.getTermVector().get(token);
                            
                            count += pre_count;
                            
                            this.getTermVector().put(token, count);
                        } else {
                            this.getTermVector().put(token, count);
                        }
                    }
                }
            }
        }
        
        return true;
    }

    public Map<String, Integer> getTermVector() {
        return termVector;
    }
    
    public int getNumberOfEntities() {
        return guids.size();
    }
}
